package com.ruoyi.patient.controller;


import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.patient.entity.*;
import com.ruoyi.patient.entity.order.PatientOrderDetailRet;
import com.ruoyi.patient.entity.order.PatientOrderRequest;
import com.ruoyi.patient.entity.order.PatientOrderReturnVO;
import com.ruoyi.patient.service.MyCartService;
import com.ruoyi.patient.service.PatientOrderService;
import com.ruoyi.patient.service.PatientTokenService;
import com.ruoyi.patient.utils.PatientServerConfig;
import com.ruoyi.patient.utils.PatientTokenFilter;
import com.ruoyi.service.domain.ServiceOrders;
import com.ruoyi.service.domain.ServicePay;
import com.ruoyi.service.domain.ServicePicture;
import com.ruoyi.service.domain.ServiceRule;
import com.ruoyi.service.entity.pay.WxPayRespVO;
import com.ruoyi.service.entity.pay.WxPayV3Bean;
import com.ruoyi.service.service.IServiceOrdersService;
import com.ruoyi.service.service.IServicePayService;
import com.ruoyi.service.service.IServicePictureService;
import com.ruoyi.service.service.IServiceRuleService;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Transaction;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.util.*;

import static com.wechat.pay.java.core.http.Constant.*;


/**
 * 订单业务控制
 *
 * @author ZDL
 */

@RestController
@RequestMapping("/appPatient/appPatientOrder")
public class PatientOrderController {

    @Autowired
    private IServiceOrdersService serviceOrdersService;

    @Autowired
    private PatientTokenService tokenService;

    @Autowired
    private PatientTokenFilter patientTokenFilter;

    @Autowired
    private PatientOrderService patientOrderService;

    @Autowired
    private IServicePictureService servicePictureService;

    @Autowired
    private MyCartService myCartService;

    @Autowired
    private IServicePayService payService;

    @Autowired
    private IServiceRuleService ruleService;

    @Autowired
    private WxPayV3Bean wxPayV3Bean;


    //private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private PatientServerConfig serverConfig;

    @Qualifier("patientRestTemplate")
    @Autowired
    private RestTemplate restTemplate;

    private static final String FILE_DELIMETER = ",";

    /**
     * 购物车后订单初始化
     *
     * @param
     * @return 结果
     */
    @GetMapping("/initOrder")
    public AjaxResult initOrder(HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null ||oldPatient.getUserId() == null ) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息错误，请重新登录");
                return ajaxResult;
            }
            List<ItemComboReturn> itemComboReturns = patientOrderService.initOrder(oldPatient);
            return AjaxResult.success("获取成功", itemComboReturns);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }
    
    /**
     * 获取订单列表方法
     *
     * @param 
     * @return 结果
     */
    @GetMapping("/getOrderList")
    public AjaxResult getOrderList(String labelStatus, int page, int size, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null ||oldPatient.getUserId() == null ) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息错误，请重新登录");
                return ajaxResult;
            }
            if (labelStatus == null){
                labelStatus = "all";
            }
            Page<PatientOrderReturnVO> retOrderList = patientOrderService.getOrderList(labelStatus, page, size, oldPatient);
            return AjaxResult.success("获取成功", retOrderList);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 获取订单详情方法
     *
     * @param
     * @return 结果
     */
    @GetMapping("/getOrderDetail")
    public AjaxResult getOrderDetail(Long orderId, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null ||oldPatient.getUserId() == null ) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息错误，请重新登录");
                return ajaxResult;
            }
            if(orderId == null){
                return AjaxResult.warn("订单号错误");
            }
            ServiceOrders oldOrder = serviceOrdersService.selectServiceOrdersByOrderId(orderId);
            if(oldOrder.getOrderUserid() != oldPatient.getUserId()){
                return AjaxResult.warn("不是该用户订单错误");
            }
            PatientOrderDetailRet retOrderDetail = patientOrderService.getOrderDetail(orderId, oldPatient);
            return AjaxResult.success("获取成功", retOrderDetail);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 获取订单进度方法
     *
     * @param
     * @return 结果
     */
    @GetMapping("/getOrderProcess")
    public AjaxResult getOrderProcess(Long orderId, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null ||oldPatient.getUserId() == null ) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息错误，请重新登录");
                return ajaxResult;
            }
            if(orderId == null){
                return AjaxResult.warn("订单号错误");
            }
            ServiceOrders oldOrder = serviceOrdersService.selectServiceOrdersByOrderId(orderId);
            if(oldOrder.getOrderUserid() != oldPatient.getUserId()){
                return AjaxResult.warn("不是该用户订单错误");
            }
            List<PatientOrderTimeReturn> retOrderTimeList = patientOrderService.getOrderProcess(orderId, oldPatient);
            return AjaxResult.success("获取成功", retOrderTimeList);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }


    /**
     * 新增订单方法
     *
     * @param orderBody 订单操作信息
     * @return 结果
     */
    @PostMapping("/addOrder")
    public AjaxResult addOrder(@RequestBody PatientOrderRequest orderBody, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null ||oldPatient.getUserId() == null ) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息错误，请重新登录");
                return ajaxResult;
            }
            if (orderBody.getOrders() == null || orderBody.getOrders().size() == 0){
                return AjaxResult.warn("数据空错误");
            }
            if (orderBody.getBookPersonId() == null) {
                return AjaxResult.warn("请选择被服务人");
            }
            if (orderBody.getBookDate() == null) {
                return AjaxResult.warn("请选择预定服务时间");
            }
            //List<PatientOrderRequestNode> bodyOrders = orderBody.getOrders();
            //Boolean okFlag = false;
            //for (PatientOrderRequestNode bodyOrder : bodyOrders) {
            //    if (bodyOrder.getSelectedSpecId() == 0L){
            //        okFlag = true;
            //        break;
            //    }
            //}
            //if (okFlag == false){
            //    return AjaxResult.warn("未选择必选上门服务费");
            //}
            //if (orderBody.getOrders().size() < 2){
            //    return AjaxResult.warn("请选择服务项目，以便为您指派专业护士");
            //}
            ServiceRule rule = new ServiceRule();
            rule.setRuleType("0");
            rule.setRuleDelFlag("0");
            rule.setRuleUseFlag("0");
            List<ServiceRule> ruleVOList = ruleService.selectServiceRuleListOld(rule);
            if (ruleVOList.size() > 0){
                rule = ruleVOList.get(0);
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date scheduledtime = formatter.parse(orderBody.getBookDate());

                Instant instant1 = scheduledtime.toInstant();
                Instant instant2 = (new Date()).toInstant();
                Duration duration = Duration.between(instant2, instant1);

                if (duration.toHours() < rule.getRuleHour()){
                    return AjaxResult.warn("预定时间无法服务，请重新选择");
                }
            }

            ServiceOrders newOrder = patientOrderService.newOrder(orderBody, oldPatient);
            if (newOrder != null){
                myCartService.deleteMyCartAll(oldPatient);
                Map<String, Object> data = new HashMap<>();
                data.put("orderId", newOrder.getOrderId());
                return AjaxResult.success("下单成功", data);
            } else {
                return AjaxResult.error("下单失败");
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 取消订单方法
     *
     * @param
     * @return 结果
     */
    @PostMapping("/cancelOrder")
    public AjaxResult cancelOrder(@RequestBody Map<String, Long> reqBody, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            Long orderId = reqBody.get("orderId");
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null ||oldPatient.getUserId() == null ) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息错误，请重新登录");
                return ajaxResult;
            }
            if (orderId == null){
                return AjaxResult.warn("订单号错误");
            }
            ServiceOrders oldOrder = serviceOrdersService.selectServiceOrdersByOrderId(orderId);
            if (oldOrder == null || oldOrder.getOrderUserid() != oldPatient.getUserId() ){
                return AjaxResult.warn("订单信息错误");
            }
            if (oldOrder.getOrderStatus() != 0 || oldOrder.getOrderFlag() != 0 || "2".equals(oldOrder.getOrderDelFlag()) || "2".equals(oldOrder.getOrderUseFlag()) || oldOrder.getOrderServiceflag() != 1){
                return AjaxResult.warn("订单状态现无法取消");
            }

            if (patientOrderService.cancelOrder(orderId, oldPatient)){
                Map<String, Object> data = new HashMap<>();
                data.put("flag", true);
                return AjaxResult.success("取消成功", data);
            } else {
                Map<String, Object> data = new HashMap<>();
                data.put("flag", false);
                return AjaxResult.error("取消失败", data);
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 订单支付方法
     *
     * @param
     * @return 结果
     */
    @PostMapping("/payOrder")
    public AjaxResult payOrder(@RequestBody Map<String, Long> reqBody, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            Long orderId = reqBody.get("orderId");
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null ||oldPatient.getUserId() == null ) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息错误，请重新登录");
                return ajaxResult;
            }
            if (orderId == null){
                return AjaxResult.warn("订单号错误");
            }
            ServiceOrders oldOrder = serviceOrdersService.selectServiceOrdersByOrderId(orderId);
            if (oldOrder == null ||oldOrder.getOrderUserid() != oldPatient.getUserId()){
                return AjaxResult.warn("订单信息错误");
            }
            if (oldOrder.getOrderStatus() != 0 || oldOrder.getOrderFlag() != 0 || "2".equals(oldOrder.getOrderDelFlag())){
                return AjaxResult.warn("订单状态错误");
            }
            //if (orderBody.getPayMoney() == null || orderBody.getPayMoney() <= 0 || orderBody.getPayCode() == null || orderBody.getPayType() == null) {
            //    return AjaxResult.warn("支付信息信息错误");
            //}

            WxPayRespVO result = patientOrderService.payOrder(orderId, oldPatient, request);

            if (result != null && result.getPaySign() != null) {
                Map<String, Object> data = new HashMap<>();
                data.put("flag", true);
                data.put("data", result);
                return AjaxResult.success("下单成功", data);
            }else {
                Map<String, Object> data = new HashMap<>();
                data.put("flag", false);
                data.put("data", result);
                return AjaxResult.error("下单失败", data);
            }
            //Integer code = result.getInt("code");
            //String msg = result.getString("msg");
            //if (code != null && code == 0){
            //    String data = result.getString("data");
            //    Map<String, Object> dataRet = new HashMap<>();
            //    dataRet.put("flag", true);
            //    if (data != null) dataRet.put("data", data);
            //    return AjaxResult.success(msg, dataRet);
            //} else {
            //    Map<String, Object> dataRet = new HashMap<>();
            //    dataRet.put("flag", false);
            //    //if (data != null) dataRet.put("data", data);
            //    return AjaxResult.error(msg, dataRet);
            //}
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 订单支付通知方法
     *
     * @param
     * @return 结果
     */
    @PostMapping("/notifyPay")
    public AjaxResult notifyPay(HttpServletRequest request) {
        try {

            //读取请求体的信息
            ServletInputStream inputStream = request.getInputStream();
            StringBuffer stringBuffer = new StringBuffer();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String s;
            //读取回调请求体
            while ((s = bufferedReader.readLine()) != null) {
                stringBuffer.append(s);
            }
            String s1 = stringBuffer.toString();
            String timestamp = request.getHeader(WECHAT_PAY_TIMESTAMP);
            String nonce = request.getHeader(WECHAT_PAY_NONCE);
            String signType = request.getHeader("Wechatpay-Signature-Type");
            String serialNo = request.getHeader(WECHAT_PAY_SERIAL);
            String signature = request.getHeader(WECHAT_PAY_SIGNATURE);
            // 如果已经初始化了 RSAAutoCertificateConfig，可直接使用
            // 没有的话，则构造一个
            //log.error(JSON.toJSONString(wxPayV3Bean));
            NotificationConfig config = new RSAAutoCertificateConfig.Builder()
                    .merchantId(wxPayV3Bean.getMchId())
                    .privateKeyFromPath(wxPayV3Bean.getKeyPath())
                    .merchantSerialNumber(wxPayV3Bean.getMchSerialNo())
                    .apiV3Key(wxPayV3Bean.getApiKey())
                    .build();
            // 初始化 NotificationParser
            NotificationParser parser = new NotificationParser(config);

            RequestParam requestParam=new RequestParam.Builder()
                            .serialNumber(serialNo)
                            .nonce(nonce)
                            .signature(signature)
                            .timestamp(timestamp)
                            // 若未设置signType，默认值为 WECHATPAY2-SHA256-RSA2048
                            .signType(signType)
                            .body(s1)
                            .build();
            Transaction parse = parser.parse(requestParam, Transaction.class);
            System.out.println("parse = " + parse);
            //parse.getTradeState().equals("SUCCESS");说明支付成功
            if (parse.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)) {
                //你的业务代码
                String orderCode = parse.getOutTradeNo();
                String transactionId = parse.getTransactionId();


                if (orderCode == null) {
                    AjaxResult ajaxResult = new AjaxResult();
                    ajaxResult.put("return_code", "FAIL");
                    ajaxResult.put("return_msg", "订单号错误");
                    return ajaxResult;
                }
                ServiceOrders oldOrder = serviceOrdersService.selectServiceOrdersByOrderCode(orderCode);

                if (oldOrder == null) {
                    AjaxResult ajaxResult = new AjaxResult();
                    ajaxResult.put("return_code", "FAIL");
                    ajaxResult.put("return_msg", "订单信息错误");
                    return ajaxResult;
                }
                if (oldOrder.getOrderStatus() != 0 || oldOrder.getOrderFlag() != 0 || "2".equals(oldOrder.getOrderDelFlag()) || oldOrder.getOrderServiceflag() != 1) {
                    AjaxResult ajaxResult = new AjaxResult();
                    ajaxResult.put("return_code", "FAIL");
                    ajaxResult.put("return_msg", "订单状态错误");
                    return ajaxResult;
                }
                ServicePay pay = payService.selectServicePayByPayId(oldOrder.getOrderPay());
                if (pay == null) {
                    AjaxResult ajaxResult = new AjaxResult();
                    ajaxResult.put("return_code", "FAIL");
                    ajaxResult.put("return_msg", "订单支付信息错误");
                    return ajaxResult;
                }
                if (("0".equals(pay.getPayStatus())) && ("1".equals(pay.getPayStatusfinish()))) {
                    if (patientOrderService.notifyFinish(oldOrder.getOrderId(), transactionId)) {
                        AjaxResult ajaxResult = new AjaxResult();
                        ajaxResult.put("return_code", "SUCCESS");
                        return ajaxResult;
                    } else {
                        AjaxResult ajaxResult = new AjaxResult();
                        ajaxResult.put("return_code", "FAIL");
                        ajaxResult.put("return_msg", "更新失败");
                        return ajaxResult;
                    }
                }
                if ("1".equals(pay.getPayStatus())) {
                    if (patientOrderService.notifyPay(oldOrder.getOrderId(), transactionId)) {
                        AjaxResult ajaxResult = new AjaxResult();
                        ajaxResult.put("return_code", "SUCCESS");
                        return ajaxResult;
                    } else {
                        AjaxResult ajaxResult = new AjaxResult();
                        ajaxResult.put("return_code", "FAIL");
                        ajaxResult.put("return_msg", "更新失败");
                        return ajaxResult;
                    }
                }
            }else{
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("return_code", "FAIL");
                ajaxResult.put("return_msg", "微信平台支付失败");
                return ajaxResult;
            }

        }catch (Exception e){
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("return_code", "FAIL");
            ajaxResult.put("return_msg", "e.getMessage()");
            return ajaxResult;
        }
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("return_code", "FAIL");
        ajaxResult.put("return_msg", "返回信息错误");
        return ajaxResult;
    }


    /**
     * 订单退款方法
     *
     * @param
     * @return 结果
     */
    @PostMapping("/refundOrder")
    public AjaxResult refundOrder(@RequestBody Map<String, Long> reqBody, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            Long orderId = reqBody.get("orderId");
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient.getUserId() == null) {
                return AjaxResult.warn("用户信息错误");
            }
            if (orderId == null){
                return AjaxResult.warn("订单号错误");
            }
            ServiceOrders oldOrder = serviceOrdersService.selectServiceOrdersByOrderId(orderId);
            if (oldOrder == null || oldOrder.getOrderUserid() != oldPatient.getUserId()){
                return AjaxResult.warn("订单信息错误");
            }
            if (oldOrder.getOrderStatus() != 0 || oldOrder.getOrderFlag() != 0){
                return AjaxResult.warn("订单状态错误");
            }
            if (oldOrder.getOrderServiceflag() > 7 || oldOrder.getOrderServiceflag() == 2 || oldOrder.getOrderServiceflag() == 4){
                return AjaxResult.warn("订单状态错误，请联系医院退款！");
            }

            ServiceRule rule = new ServiceRule();
            rule.setRuleFlag(oldOrder.getOrderServiceflag());
            rule.setRuleType("1");
            rule.setRuleDelFlag("0");
            rule.setRuleUseFlag("0");
            Double refundBit = 1.0;
            List<ServiceRule> ruleVOList = ruleService.selectServiceRuleListOld(rule);
            if (ruleVOList.size() > 0){
                rule = ruleVOList.get(0);
                refundBit = rule.getRuleRefund();
            }

            if (patientOrderService.refundOrder(orderId, refundBit, oldPatient)){
                Map<String, Object> data = new HashMap<>();
                data.put("flag", true);
                return AjaxResult.success("退款申请成功", data);
            } else {
                Map<String, Object> data = new HashMap<>();
                data.put("flag", true);
                return AjaxResult.error("退款申请失败", data);
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 订单退款通知方法
     *
     * @param orderBody 订单操作信息
     * @return 结果
     */
    @PostMapping("/notifyRefund")
    public AjaxResult notifyRefund(@RequestBody PatientOrderBody orderBody, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient.getUserId() == null || oldPatient.getUserId() != orderBody.getOrderUserid()) {
                return AjaxResult.warn("用户信息错误");
            }
            if (orderBody.getOrderId() == null){
                return AjaxResult.warn("订单号错误");
            }
            ServiceOrders oldOrder = serviceOrdersService.selectServiceOrdersByOrderId(orderBody.getOrderId());
            if (oldOrder.getOrderUserid() != oldPatient.getUserId() || oldOrder == null){
                return AjaxResult.warn("订单信息错误");
            }
            if (oldOrder.getOrderStatus() != 0 || oldOrder.getOrderFlag() != 0 || oldOrder.getOrderServiceflag() != 3){
                return AjaxResult.warn("订单状态错误");
            }
            orderBody.setOrderPay(oldOrder.getOrderPay());
            if (patientOrderService.notifyRefund(orderBody, oldPatient)){
                return AjaxResult.success("退款成功");
            } else {
                return AjaxResult.error("退款失败");
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 订单修改信息方法
     *
     * @param orderBody 订单操作信息
     * @return 结果
     */
    @PostMapping("/modifyOrder")
    public AjaxResult modifyOrder(@RequestBody OrderModifyRequest orderBody, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null || oldPatient.getUserId() == null ) {
                return AjaxResult.warn("用户信息错误");
            }
            if (orderBody.getOrderId() == null){
                return AjaxResult.warn("订单号错误");
            }
            ServiceOrders oldOrder = serviceOrdersService.selectServiceOrdersByOrderId(orderBody.getOrderId());
            if (oldOrder.getOrderUserid() != oldPatient.getUserId() || oldOrder == null){
                return AjaxResult.warn("订单信息错误");
            }
            if (oldOrder.getOrderStatus() != 0 || oldOrder.getOrderFlag() != 0 || "2".equals(oldOrder.getOrderDelFlag()) || oldOrder.getOrderServiceflag() > 8){
                return AjaxResult.warn("订单当前状态不允许修改信息");
            }

            if (patientOrderService.modifyOrder(orderBody, oldPatient)){
                Map<String, Object> data = new HashMap<>();
                data.put("flag", true);
                return AjaxResult.success("修改成功", data);
            } else {
                Map<String, Object> data = new HashMap<>();
                data.put("flag", false);
                return AjaxResult.error("修改失败", data);
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 订单最终结算方法
     *
     * @param
     * @return 结果
     */
    @PostMapping("/payDiff")
    public AjaxResult payFinishOrder(@RequestBody Map<String, Long> reqBody, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            Long orderId = reqBody.get("orderId");
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient.getUserId() == null ) {
                return AjaxResult.warn("用户信息错误");
            }
            if (orderId == null){
                return AjaxResult.warn("订单号错误");
            }
            ServiceOrders oldOrder = serviceOrdersService.selectServiceOrdersByOrderId(orderId);
            if (oldOrder == null || oldOrder.getOrderUserid() != oldPatient.getUserId()){
                return AjaxResult.warn("订单信息错误");
            }
            if (oldOrder.getOrderFlag() != 0 || oldOrder.getOrderServiceflag() != 12){
                return AjaxResult.warn("订单状态错误");
            }
            JSONObject result = patientOrderService.payFinishOrder(orderId, oldPatient);
            Integer code = result.getInt("code");
            String msg = result.getString("msg");
            String data = result.getString("data");
            if (code != null && code == 0){
                Map<String, Object> dataRet = new HashMap<>();
                dataRet.put("flag", true);
                if (data != null) dataRet.put("data", data);
                return AjaxResult.success(msg, dataRet);
            } else {
                Map<String, Object> dataRet = new HashMap<>();
                dataRet.put("flag", false);
                if (data != null) dataRet.put("data", data);
                return AjaxResult.error(msg, dataRet);
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 订单最终结算通知方法
     *
     * @param
     * @return 结果
     */
    //@PostMapping("/notifyDiff")
    //public AjaxResult notifyDiff(@RequestBody Map<String, String> reqBody, HttpServletRequest request) {
    //    try {
    //        if(!patientTokenFilter.doFilterInternal(request)) {
    //            AjaxResult ajaxResult = new AjaxResult();
    //            ajaxResult.put("code", 401);
    //            ajaxResult.put("msg", "用户信息过期，请重新登录");
    //            return ajaxResult;
    //        }
    //        Long orderId = Long.valueOf(reqBody.get("orderId"));
    //        String orderCode = reqBody.get("orderCode");
    //        LoginPatient oldPatient = tokenService.getLoginUser(request);
    //        if (oldPatient.getUserId() == null ) {
    //            return AjaxResult.warn("用户信息错误");
    //        }
    //        if (orderId == null){
    //            return AjaxResult.warn("订单号错误");
    //        }
    //        ServiceOrders oldOrder = serviceOrdersService.selectServiceOrdersByOrderId(orderId);
    //        if (oldOrder == null || oldOrder.getOrderUserid() != oldPatient.getUserId()){
    //            return AjaxResult.warn("订单信息错误");
    //        }
    //        if (oldOrder.getOrderFlag() != 0 || oldOrder.getOrderServiceflag() != 12){
    //            return AjaxResult.warn("订单状态错误");
    //        }
    //
    //        if (patientOrderService.notifyFinish(orderId)){
    //            return AjaxResult.success("支付成功");
    //        } else {
    //            return AjaxResult.error("支付失败");
    //        }
    //    }catch (Exception e){
    //        return AjaxResult.error(e.getMessage());
    //    }
    //}


    /**
     * 订单用户评价方法
     *
     * @param assessBody 订单用户评价信息
     * @return 结果
     */
    @PostMapping("/assessOrder")
    public AjaxResult assessOrder(@RequestBody PatientAssessReq assessBody, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null || oldPatient.getUserId() == null) {
                return AjaxResult.warn("用户信息错误");
            }
            if (assessBody.getOrderId() == null){
                return AjaxResult.warn("订单号错误");
            }
            ServiceOrders oldOrder = serviceOrdersService.selectServiceOrdersByOrderId(assessBody.getOrderId());
            if (oldOrder.getOrderUserid() != oldPatient.getUserId() || oldOrder == null){
                return AjaxResult.warn("订单信息错误");
            }
            if (oldOrder.getOrderStatus() != 0 || oldOrder.getOrderFlag() != 0 || oldOrder.getOrderServiceflag() < 11){
                return AjaxResult.warn("订单状态错误");
            }
            if (assessBody.getContent() == null) {
                return AjaxResult.warn("用户评价信息错误");
            }
            if (patientOrderService.assessOrder(assessBody, oldPatient)){
                Map<String, Object> data = new HashMap<>();
                data.put("flag", true);
                return AjaxResult.success("评价完成", data);
            } else {
                Map<String, Object> data = new HashMap<>();
                data.put("flag", false);
                return AjaxResult.error("评价失败", data);
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 删除订单方法
     *
     * @param
     * @return 结果
     */
    @PostMapping("/deleteOrder")
    public AjaxResult deleteOrder(@RequestBody Map<String, Long> reqBody, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            Long orderId = reqBody.get("orderId");
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient.getUserId() == null ) {
                return AjaxResult.warn("用户信息错误");
            }
            if (orderId == null){
                return AjaxResult.warn("订单号错误");
            }
            ServiceOrders oldOrder = serviceOrdersService.selectServiceOrdersByOrderId(orderId);
            if (oldOrder == null || oldOrder.getOrderUserid() != oldPatient.getUserId() ){
                return AjaxResult.warn("订单信息错误");
            }
            if (oldOrder.getOrderStatus() != 0 || oldOrder.getOrderFlag() != 0 || !"0".equals(oldOrder.getOrderDelFlag())  || oldOrder.getOrderServiceflag() < 15){
                return AjaxResult.warn("订单状态错误");
            }

            if (patientOrderService.deleteOrder(orderId, oldPatient)){
                Map<String, Object> data = new HashMap<>();
                data.put("flag", true);
                return AjaxResult.success("删除成功", data);
            } else {
                Map<String, Object> data = new HashMap<>();
                data.put("flag", false);
                return AjaxResult.error("删除失败", data);
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 用户上传证明方法
     *
     * @param
     * @return 结果
     */
    @PostMapping("/saveProofs")
    public AjaxResult saveProofs(@RequestBody PatientPictureRequest imagesInfo, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null || oldPatient.getUserId() == null) {
                return AjaxResult.warn("用户信息错误");
            }
            if (imagesInfo.getOrderId() == null){
                return AjaxResult.warn("订单号错误");
            }
            if (imagesInfo.getType() == null){
                return AjaxResult.warn("上传类型错误");
            }
            ServiceOrders oldOrder = serviceOrdersService.selectServiceOrdersByOrderId(imagesInfo.getOrderId());
            if (oldOrder == null || oldOrder.getOrderUserid() != oldPatient.getUserId()){
                return AjaxResult.warn("订单信息错误");
            }
            if ("2".equals(oldOrder.getOrderDelFlag())){
                return AjaxResult.warn("订单已删除,无法上传");
            }
            if (imagesInfo.getImgUrls().size() == 0) {
                return AjaxResult.warn("请上传新照片");
            }
            ServicePicture pictureSearch = new ServicePicture();
            pictureSearch.setPictureUserid(oldPatient.getUserId());
            pictureSearch.setPictureOrderid(imagesInfo.getOrderId());
            pictureSearch.setPictureType(imagesInfo.getType());
            pictureSearch.setPictureDelFlag("0");
            List<ServicePicture> nowPictureList = servicePictureService.selectServicePictureList(pictureSearch);
            if (nowPictureList.size() + imagesInfo.getImgUrls().size() > 8){
                Map<String, Object> data = new HashMap<>();
                data.put("flag", false);
                return AjaxResult.warn("上传数量超过上限", data);
            }
            ArrayList<String> tempImagesUrl = new ArrayList<String>();
            for(String imageUrl : imagesInfo.getImgUrls()){
                tempImagesUrl.add(imageUrl.replace("@", "/"));
            }
            imagesInfo.setImgUrls(tempImagesUrl);
            //List<String> tempImagesUrl = new ArrayList<String>();
            //for(String imageUrl : imagesInfo.getImgUrls()){
            //    tempImagesUrl.add("https://img0.baidu.com/it/u=1024258047,2987031221&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=326");
            //}
            //imagesInfo.setImgUrls(tempImagesUrl);
            if ("medical".equals(imagesInfo.getType())) {
                if (patientOrderService.uploadMedical(imagesInfo, oldPatient)){
                    Map<String, Object> data = new HashMap<>();
                    data.put("flag", true);
                    return AjaxResult.success("上传成功", data);
                } else {
                    Map<String, Object> data = new HashMap<>();
                    data.put("flag", false);
                    return AjaxResult.error("上传失败", data);
                }
            }else if ("consume".equals(imagesInfo.getType())) {
                if (patientOrderService.uploadConsume(imagesInfo, oldPatient)){
                    Map<String, Object> data = new HashMap<>();
                    data.put("flag", true);
                    return AjaxResult.success("上传成功", data);
                } else {
                    Map<String, Object> data = new HashMap<>();
                    data.put("flag", false);
                    return AjaxResult.error("上传失败", data);
                }
            }else{
                return AjaxResult.warn("上传类型错误");
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    ///**
    // * 用户上传就医证明方法
    // *
    // * @param pictureBody 就医证明照片
    // * @return 结果
    // */
    //@PostMapping("/uploadHospital")
    //public AjaxResult uploadHospital(@RequestBody PatientPictureBody pictureBody, HttpServletRequest request) {
    //    try {
    //        if(!patientTokenFilter.doFilterInternal(request)) {
    //                AjaxResult ajaxResult = new AjaxResult();
    //                ajaxResult.put("code", 401);
    //                ajaxResult.put("msg", "用户信息过期，请重新登录");
    //                return ajaxResult;
    //            }
    //        LoginPatient oldPatient = tokenService.getLoginUser(request);
    //        if (oldPatient.getUserId() == null) {
    //            return AjaxResult.warn("用户信息错误");
    //        }
    //        if (pictureBody.getOrderId() == null){
    //            return AjaxResult.warn("订单号错误");
    //        }
    //        ServiceOrders oldOrder = serviceOrdersService.selectServiceOrdersByOrderId(pictureBody.getOrderId());
    //        if (oldOrder.getOrderUserid() != oldPatient.getUserId() || oldOrder == null){
    //            return AjaxResult.warn("订单信息错误");
    //        }
    //        if (pictureBody.getPicturePic() == null) {
    //            return AjaxResult.warn("照片信息错误");
    //        }
    //        ServicePicture pictureSearch = new ServicePicture();
    //        pictureSearch.setPictureUserid(oldPatient.getUserId());
    //        pictureSearch.setPictureOrderid(pictureBody.getOrderId());
    //        List<ServicePicture> nowPictureList = servicePictureService.selectServicePictureList(pictureSearch);
    //        if (nowPictureList.size()>7){
    //            return AjaxResult.warn("上传数量超过上限");
    //        }
    //        if (patientOrderService.uploadHospital(pictureBody, oldPatient)){
    //            return AjaxResult.success("上传成功");
    //        } else {
    //            return AjaxResult.error("上传失败");
    //        }
    //    }catch (Exception e){
    //        return AjaxResult.error(e.getMessage());
    //    }
    //}

    ///**
    // * 用户上传耗材证明方法
    // *
    // * @param pictureBody 就医证明照片
    // * @return 结果
    // */
    //@PostMapping("/uploadSupplies")
    //public AjaxResult uploadSupplies(@RequestBody PatientPictureBody pictureBody, HttpServletRequest request) {
    //    try {
    //        if(!patientTokenFilter.doFilterInternal(request)) {
    //                AjaxResult ajaxResult = new AjaxResult();
    //                ajaxResult.put("code", 401);
    //                ajaxResult.put("msg", "用户信息过期，请重新登录");
    //                return ajaxResult;
    //            }
    //        LoginPatient oldPatient = tokenService.getLoginUser(request);
    //        if (oldPatient.getUserId() == null) {
    //            return AjaxResult.warn("用户信息错误");
    //        }
    //        if (pictureBody.getOrderId() == null){
    //            return AjaxResult.warn("订单号错误");
    //        }
    //        ServiceOrders oldOrder = serviceOrdersService.selectServiceOrdersByOrderId(pictureBody.getOrderId());
    //        if (oldOrder.getOrderUserid() != oldPatient.getUserId() || oldOrder == null){
    //            return AjaxResult.warn("订单信息错误");
    //        }
    //        if (pictureBody.getPicturePic() == null) {
    //            return AjaxResult.warn("照片信息错误");
    //        }
    //        ServicePicture pictureSearch = new ServicePicture();
    //        pictureSearch.setPictureUserid(oldPatient.getUserId());
    //        pictureSearch.setPictureOrderid(pictureBody.getOrderId());
    //        List<ServicePicture> nowPictureList = servicePictureService.selectServicePictureList(pictureSearch);
    //        if (nowPictureList.size()>7){
    //            return AjaxResult.warn("上传数量超过上限");
    //        }
    //        if (patientOrderService.uploadHospital(pictureBody, oldPatient)){
    //            return AjaxResult.success("上传成功");
    //        } else {
    //            return AjaxResult.error("上传失败");
    //        }
    //    }catch (Exception e){
    //        return AjaxResult.error(e.getMessage());
    //    }
    //}

    /**
     * base64上传请求（单个）
     */
    //@PostMapping("/uploadBase64")
    //public AjaxResult uploadBase64File(@RequestBody Map<String, String> reqBody, HttpServletRequest request) {
    //    try {
    //        if (!patientTokenFilter.doFilterInternal(request)) {
    //            AjaxResult ajaxResult = new AjaxResult();
    //            ajaxResult.put("code", 401);
    //            ajaxResult.put("msg", "用户信息过期，请重新登录");
    //            return ajaxResult;
    //        }
    //        String fileName = reqBody.get("fileName");
    //        String fileContent = reqBody.get("fileContent");
    //
    //        if (StringUtils.isEmpty(fileName) || StringUtils.isEmpty(fileContent)) {
    //            return AjaxResult.warn("文件信息错误");
    //        }
    //
    //        // 去掉Base64前缀（例如 "data:image/jpeg;base64,"）
    //        String base64Image = fileContent.split(",")[1];
    //        byte[] imageBytes = Base64.getDecoder().decode(base64Image);
    //
    //        // 上传文件路径
    //        String filePath = RuoYiConfig.getUploadPath();
    //        String newFileName = FileUtils.getName(fileName);
    //        String fullPath = filePath + newFileName;
    //
    //        // 保存文件
    //        MultipartFile multipartFile = new PatientMultipartFile(imageBytes, "file", fileName, "image/jpeg");
    //
    //        // 上传并返回新文件名称
    //        fileName = FileUploadUtils.upload(filePath, multipartFile);
    //        String url = serverConfig.getUrl() + fileName;
    //        AjaxResult ajax = AjaxResult.success();
    //        ajax.put("url", url);
    //        ajax.put("fileName", fileName);
    //        ajax.put("newFileName", FileUtils.getName(fileName));
    //        ajax.put("originalFilename", multipartFile.getOriginalFilename());
    //        return ajax;
    //
    //    } catch (Exception e) {
    //        return AjaxResult.error(e.getMessage());
    //    }
    //}

    /**
     * base64上传请求（单个-表单）
     */
    //@PostMapping("/uploadForm")
    //public AjaxResult uploadForm(Object file, HttpServletRequest request) {
    //    try {
    //        String headerValue = request.getHeader("Authorization");
    //        String paramValue = request.getParameter("file");
    //
    //        return AjaxResult.success("信息："+paramValue,headerValue);
    //
            //if (!patientTokenFilter.doFilterInternal(request)) {
            //    AjaxResult ajaxResult = new AjaxResult();
            //    ajaxResult.put("code", 401);
            //    ajaxResult.put("msg", "用户信息过期，请重新登录");
            //    return ajaxResult;
            //}
            //LoginPatient oldPatient = tokenService.getLoginUser(request);
            //if (oldPatient == null || oldPatient.getUserId() == null) {
            //    return AjaxResult.warn("用户信息错误");
            //}
            //String fileName = oldPatient.getUser().getUsersName();
            //String fileContent = file.toString();
            //
            //if (StringUtils.isEmpty(fileName) || StringUtils.isEmpty(fileContent)) {
            //    return AjaxResult.warn("文件信息错误，入参：" + file);
            //}
            //
            //// 去掉Base64前缀（例如 "data:image/jpeg;base64,"）
            //String base64Image = fileContent.split(",")[1];
            //byte[] imageBytes = Base64.getDecoder().decode(base64Image);
            //
            //// 上传文件路径
            //String filePath = RuoYiConfig.getUploadPath();
            //String newFileName = FileUtils.getName(fileName);
            //String fullPath = filePath + newFileName;
            //
            //// 保存文件
            //MultipartFile multipartFile = new PatientMultipartFile(imageBytes, "file", fileName, "image/jpeg");
            //
            //// 上传并返回新文件名称
            //fileName = FileUploadUtils.upload(filePath, multipartFile);
            //String url = serverConfig.getUrl() + fileName;
            //AjaxResult ajax = AjaxResult.success();
            //ajax.put("url", url);
            //ajax.put("fileName", fileName);
            //ajax.put("newFileName", FileUtils.getName(fileName));
            //ajax.put("originalFilename", multipartFile.getOriginalFilename());
            //return ajax;
    //
    //    } catch (Exception e) {
    //        return AjaxResult.error(e.getMessage());
    //    }
    //}

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file, HttpServletRequest request) throws Exception
    {
        try
        {
            if (!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files, HttpServletRequest request) throws Exception
    {
        try
        {
            if (!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取订单取消原因方法
     *
     * @param
     * @return 结果
     */
    @GetMapping("/getOrderCancelReason")
    public AjaxResult getOrderCancelReason(Long orderId, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null || oldPatient.getUserId() == null) {
                return AjaxResult.warn("用户信息错误");
            }
            if (orderId == null){
                return AjaxResult.warn("订单号错误");
            }
            ServiceOrders oldOrder = serviceOrdersService.selectServiceOrdersByOrderId(orderId);
            if (oldOrder == null || oldOrder.getOrderUserid() != oldPatient.getUserId() ){
                return AjaxResult.warn("订单信息错误");
            }
            if (oldOrder.getOrderStatus() != 0 || oldOrder.getOrderFlag() != 0){
                return AjaxResult.warn("订单状态错误");
            }

            refundRspTemp reasonReturnList = patientOrderService.getOrderCancelReason(orderId, oldPatient);
            return AjaxResult.success("获取成功", reasonReturnList);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 删除已上传文件方法
     *
     * @param
     * @return 结果
     */
    @PostMapping("/deleteFile")
    public AjaxResult deleteFile(@RequestBody Map<String, Object> reqBody, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            Long orderId = Long.parseLong(reqBody.get("orderId").toString());
            String imageUrl = reqBody.get("imageUrl").toString();
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null || oldPatient.getUserId() == null) {
                return AjaxResult.warn("用户信息错误");
            }

            Boolean flag = patientOrderService.deleteFile(orderId, imageUrl, oldPatient);
            if (flag){
                Map<String, Object> data = new HashMap<>();
                data.put("flag", true);
                return AjaxResult.success("删除成功", data);
            }else {
                Map<String, Object> data = new HashMap<>();
                data.put("flag", false);
                return AjaxResult.success("删除失败", data);
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 保存用户权限
     *
     * @param
     * @return 结果
     */
    @PostMapping("/saveNotify")
    public AjaxResult saveNotify(@RequestBody List<Map<String, Object>> templates, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient == null || oldPatient.getUserId() == null) {
                return AjaxResult.warn("用户信息错误");
            }

            Boolean flag = patientOrderService.saveNotify(templates, oldPatient);
            if (flag){
                Map<String, Object> data = new HashMap<>();
                data.put("flag", true);
                return AjaxResult.success("保存成功", data);
            }else {
                Map<String, Object> data = new HashMap<>();
                data.put("flag", false);
                return AjaxResult.success("保存失败", data);
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }

    ///**
    // * 推送测试
    // *
    // * @param
    // * @return 结果
    // */
    //@PostMapping("/testMsg")
    //public AjaxResult testMsg() {
    //    try {
    //
    //        Boolean flag = patientOrderService.addPayProcess(73L, 1L);
    //        if (flag){
    //            Map<String, Object> data = new HashMap<>();
    //            data.put("flag", true);
    //            return AjaxResult.success("推送成功", data);
    //        }else {
    //            Map<String, Object> data = new HashMap<>();
    //            data.put("flag", false);
    //            return AjaxResult.success("推送失败", data);
    //        }
    //    }catch (Exception e){
    //        return AjaxResult.error(e.getMessage());
    //    }
    //
    //
    //}

}
